package com.heima.wemedia.service.impl;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.common.enums.TaskTypeEnum;
import com.heima.model.schedule.dtos.TaskDto;
import com.heima.model.wemedia.pojos.WmNews;
import com.heima.schedule.IScheduleClient;
import com.heima.wemedia.service.WmAutoScanService;
import com.heima.wemedia.service.WmTaskService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Async;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Service;

import java.nio.charset.StandardCharsets;

/**
 * @author 陈辉
 * @data 2023 16:15
 */
@Service
@Slf4j
public class WmTaskServiceImpl implements WmTaskService {
    @Autowired
    private IScheduleClient iScheduleClient;
    @Autowired
    private WmAutoScanService wmAutoScanService;

    /**
     * 添加任务
     *
     * @param wmNews
     */
    @Override
    @Async
    public void addTask(WmNews wmNews) {
        //封装TaskDto
        TaskDto taskDto = new TaskDto();
        taskDto.setTaskType(TaskTypeEnum.NEWS_SCAN_TIME.getTaskType());      //任务类型
        taskDto.setPriority(TaskTypeEnum.NEWS_SCAN_TIME.getPriority());      //任务优先级
        taskDto.setParameters(String.valueOf(wmNews.getId()).getBytes(StandardCharsets.UTF_8));    //任务执行参数
        taskDto.setExecuteTime(wmNews.getPublishTime().getTime());   //任务执行时间

        //远程调用延迟任务微服务来添加任务
        iScheduleClient.addTask(taskDto);
    }

    /**
     * 定时拉取任务：文章审核
     * 执行频次： 每秒一次
     */
    @Override
//    @Scheduled(cron = "0/1 * * * * ?")
    public void popTask() {
        ResponseResult result = iScheduleClient.pullTask(TaskTypeEnum.NEWS_SCAN_TIME.getTaskType(),
                TaskTypeEnum.NEWS_SCAN_TIME.getPriority());
        if (result.getCode().equals(200)) {
            Object data = result.getData();
            if (data != null){
                String taskJson = data.toString();
                TaskDto taskDto = JSON.parseObject(taskJson, TaskDto.class);
                int newsId = Integer.parseInt(new String(taskDto.getParameters()));
                log.info("------------------定时拉取审核文章的任务执行了，本次审核文章id：{}",newsId);
                wmAutoScanService.autoScan(newsId);
            }
        }
    }
}
